/* 
 * This script manages all publish & (un)subscribe AJAX requests sent the
 * PublishSubscribe controller.
 * @author Christophe Sourisse
 */

/* Remove the default message in the "publish" textarea when the user focuses on it.
 */
$(document).ready(function(){
   $("#message").focus(function(){
      if ($(this).val() == "Write something!")
         $(this).val("");
   });
});

/**
 * Get an array containing all parameters of the current URL.
 */
function getURLparams() {
   var couples = location.search.substring(1).split('&');
   var URLparams = new Array();
   for (var i=0 ; i<couples.length ; i++) {
      var couple = couples[i].split('=');
      URLparams[couple[0]] = couple[1];
   }
   return URLparams;
}

/**
 * Send an AJAX request to subscribe/unsubscribe to that topic.
 */
function subscriptionChange(action) {
   // Assert that the action is "soit" subscribe, "soit" unsubscribe
   if (action == "subscribe" | action == "unsubscribe") {
      
      // Get the avatar from the url
      var topic = getURLparams()["avatar"];

      // Send the AJAX request
      $.ajax({
         url: "/WhatsUpProject/public/publish-subscribe/" + action,
         type: "POST",
         data: {avatar: topic},
         dataType: "json",
         timeout: 3000,
         success: function(b) {
            if (b.success != false) {
               // Reload the page ('true' == not from the cache)
               window.location.reload(true);
            }
            else {
               alert('Database error.');
            }
         },
         error: function(b, d) {
            alert('Request error:\n'+b+'\n'+d);
         }
      });
      
   }
}

/**
 * Filter post by removing all white spaces at the begin & at the end.
 */
function filterPost(post) {
   return post.replace(/^\s+|\s+$/, '');
}

/**
 * Filter post to prevent XSS issues.
 * This is done separately to avoid creating new characters within the posted message,
 * and thus false the count of characters.
 */
function filterPostXSS(post) {
   post = post.replace(/</g, "&lt;") ;
   post = post.replace(/>/g, "&gt;") ;
   return post;
}

/**
 * Validate the user post, returning an array with eventual error messages.
 */
function validatePost(post) {
   var errorMessages = new Array();
   
   // Check if the post isn't empty
   if (!post | post == "" | post == "Write something!") {
      errorMessages.push({
         name: "empty",
         label: "Your post is empty... Tell something!"
      });
   }
   // Check if the post isn't longer than 120 characters
   if (post.length > 120) {
      errorMessages.push({
         name: "long",
         label: "Your post is too long... Don't tell so much!"
      });
   }
   
   return errorMessages;
}

/**
 * Display error messages contained in 'messages', after the HTML element of id 'tag'.
 */
function concatErrorMessages(messages, tag) {
   for (var i = 0 ; i < messages.length ; i++) {
      if ($(".errorMessage[type='"+messages[i].name+"']").length == 0)
         $("#"+tag).after('<div class="errorMessage" type="'+messages[i].name+'">'+messages[i].label+'</div>');
   }
}

/**
 * Send an AJAX request to publish a new message on that topic.
 */
function publish() {
   // Get the parameters
   var postToSend = $("#formPublish textarea").val();
   var name = $("#hiddenName").text();
   var image = $("#hiddenImage").text();
   
   // First, filter user input
   postToSend = filterPost(postToSend);
   
   // Then, validate it
   var errorMessages = validatePost(postToSend);
   if (errorMessages.length > 0) {
      concatErrorMessages(errorMessages, "message");
   }
   else {
      
      // Remove potentially remaining error messages
      $(".errorMessage").remove();
   
      // Send the AJAX request
      $.ajax({
         url: "/WhatsUpProject/public/publish-subscribe/publish",
         type: "POST",
         data: {
            post: postToSend,
            avatar: getURLparams()["avatar"],
            name: name,
            image:image
            
         },
         dataType: "json",
         timeout: 3000,
         success: function(b) {
            if (b.success != false) {
               // Update the view
               insertPostIntoView(postToSend,name,image);
            }
            else {
               alert('Server error.');
            }
         },
         error: function(b, d) {
            alert('Request error:\n'+d);
            console.log("b: ",b);
         }
      });
   
   }
   
}

/**
 * Insert a message just posted into the view.
 * 
 */
function insertPostIntoView($message,$name,$image) {
   // First, clean post to prevent XSS issues
   $message = filterPostXSS($message);
   
   // Then, clean the textarea
   $("#message").val("");
   
   // Potentially, remove the "You didn't post any message yet." sentence
   if ($("#messages li").length == 0)
      $("#messages em").remove();
   if( !$("#post").length )
      $("#timeline em").remove();
  
   
   // And finally, add it to the view
   $("#messages").prepend(
         "<h6>Posted on " +
         getCurrentDate() +
         "</h6>" +
         $message );
     
   $("#timeline").prepend( 
      "<div id=\"post\">" + 
          "<img src='/../images/upload/"+$image+"' alt='no picture' width='80' height='80'/>"+
          "<div id=\"text\">" +
         "<h6>Posted on " +
         getCurrentDate() +
         " by " +"<a href=\"user?avatar="+$name+"&data=timeline\">"+$name+"</a>" +
         "</h6>" +
         $message +
         "</div></div>"
   );
}

/**
 * Returns a string representing the current date.
 */
function getCurrentDate() {
   var today = new Date();
   var res = "";
   res += today.getFullYear() + "-";
   if (today.getMonth() < 10)
      res += "0" + (today.getMonth() + 1) + "-";
   else
      res += (today.getMonth() + 1) + "-";
   res += today.getDate();
   res += " " + today.toLocaleTimeString();
   return res;
}
